<template>
  <!-- 指标组件 -->
  <div class="ranking" v-loading="loading">
    <div class="ranking-title">
      <!-- <span>排行</span> -->
      <span>{{ chartName }}</span>
    </div>
    <div class="ranking-date">
      <div class="ranking-date-div">
        <!-- 日期 -->
        <p v-if="screenTime && screenTime.length != 0">
          <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new
            Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
        </p>
        <!-- el-tooltip -->
        <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
          <el-tooltip content="筛选时段" placement="bottom" effect="light">
            <img class="right" :src="dateIcon" alt="">
          </el-tooltip>
        </p>
      </div>
      <!-- select -->
      <el-select v-if="options.length != 0" v-model="queryConditionVal" clearable placeholder="请选择"
        @change="handleChange">
        <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
    </div>
    <div class="ranking-echartsTitle">
      <span class="left"></span>
      <span class="right"></span>
    </div>
    <!-- echarts -->
    <div v-if="payloadData.data && payloadData.data.y.length != 0" :id="'rankingCharts' + id" class="ranking-echarts"
      style="width: 100%;height: 272px;"></div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import * as echarts from 'echarts';
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  merchantReportQueryData,
  merchantReportQueryCondition
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js'
export default {
  name: 'Ranking',
  components: {},
  props: {
    id: {
      type: String,
      default: () => {
        return null;
      }
    },
    chartName: {
      type: String,
      default: () => {
        return '';
      }
    }
  },
  inject: ['actId'],
  data() {
    return {
      loading: false,
      dateIcon,
      emptyImg,
      data: {},
      payloadData: {},
      relativelyTimeDeal: null,
      queryConditionVal: '',
      queryConditionKey: '',
      options: []
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.merchantReportQueryDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
      },
      deep: true
    }
  },
  mounted() {
    this.merchantReportQueryConditionApi();
  },
  methods: {
    handleChange(val) {
      this.merchantReportQueryDataApi();
    },
    // 获取条件切换接口
    async merchantReportQueryConditionApi() {
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let res = await merchantReportQueryCondition({
        startTime,
        endTime,
        chartType: 3,
        toIndex: 10,
        beanName: this.id,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      })
      this.options = []
      if (res.code === 200) {
        if (res.payload.length != 0) {
          res.payload.forEach(item => {
            this.options.push(...item.options)
          })

          this.queryConditionVal = this.options[0].value || '';
          this.queryConditionKey = res.payload[0].key || '';
        }
        this.merchantReportQueryDataApi();
      }
    },
    // 获取报表数据
    async merchantReportQueryDataApi() {
      this.loading = true;
      // screenTime为菜单筛选时间
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let paramStr = {
        startTime,
        endTime,
        chartType: 3,
        toIndex: 10,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      }
      paramStr[this.queryConditionKey] = this.queryConditionVal;
      const obj=store.state.user.queryConditionObj
      store.commit('SETQUERYCONDITIONOBJ', {...obj,[`${this.id}Key`]:this.queryConditionVal})
    
      paramStr = JSON.stringify(paramStr);
      let res = await merchantReportQueryData({
        beanName: this.id,
        param: paramStr
      })
      if (res.code === 200) {
        this.payloadData = res.payload;
        this.capsulationDealData()
      }
      this.loading = false;
    },
    // 数据处理
    capsulationDealData(currentIndex) {
      // 按照图表处理数据
      let ydata = [];
      let xdata = [];
      if (!this.payloadData.data) {
        return false;
      }
      let valueData = this.payloadData.data.y;
      valueData.forEach(item => {
        ydata.push(item[0].name);
        xdata.push(Number(item[0].val));
      })
      ydata = ydata.reverse();
      xdata = xdata.reverse();
      this.$nextTick(() => {
        if (valueData.length != 0) {
          console.log('drawCharts', ydata, xdata)
          this.drawCharts(ydata, xdata);
        }
      })
    },
    drawCharts(ydata, xdata) {
      let myChart = echarts.init(document.getElementById('rankingCharts' + this.id));
      //清除残留数据
      myChart.clear()
      // let ydata = ['数据7', '数据6', '数据5', '数据4', '数据3', '数据2', '数据1'];
      // let xdata = [ 116, 117, 118, 119, 420, 521, 529];
      let option = {
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "20",
          right: "50",
          bottom: "0",
          top: "10",
          containLabel: false,
        },
        xAxis: {
          type: "value",
          show: false,
        },
        yAxis: {
          type: "category",
          data: ydata,
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: false,
          },

          // axisLabel: {
          //   show:true,
          //   margin: 70,
          //   width: 70,
          //   align: "left",
          //   overflow: "truncate",
          //   formatter: function (value, index) {
          //     let ind = index + 1;
          //     if (ind == ydata.length) {
          //       return "{one|" + (ydata.length - index) + "} {a|" + value + "}";
          //     } else if (ind + 1 == ydata.length) {
          //       return "{two|" + (ydata.length - index) + "} {b|" + value + "}";
          //     } else if (ind + 2 == ydata.length) {
          //       return (
          //         "{three|" + (ydata.length - index) + "} {c|" + value + "}"
          //       );
          //     }
          //     if (ydata.length - index > 9) {
          //       return (
          //         "{five|" + (ydata.length - index) + "} {d|" + value + "}"
          //       );
          //     }
          //     return "{four|" + (ydata.length - index) + "} {d|" + value + "}";
          //   },
          //   rich: {
          //     a: {
          //       color: "#59c9f9",
          //     },
          //     b: {
          //       color: "#59c9f9",
          //     },
          //     c: {
          //       color: "#59c9f9",
          //     },
          //     d: {
          //       color: "#59c9f9",
          //     },
          //     // 第一名
          //     one: {
          //       backgroundColor: "#E86452",
          //       color: "white",
          //       width: 12,
          //       height: 16,
          //       padding: [1, 0, 0, 5],
          //       borderRadius: 10,
          //       fontSize: 11,
          //     },
          //     // 第二名
          //     two: {
          //       backgroundColor: "#FF9845",
          //       color: "white",
          //       width: 12,
          //       height: 16,
          //       padding: [1, 0, 0, 5],
          //       borderRadius: 10,
          //       fontSize: 11,
          //     },
          //     // 第三名
          //     three: {
          //       backgroundColor: "#F6BD16",
          //       color: "white",
          //       width: 12,
          //       height: 16,
          //       padding: [1, 0, 0, 5],
          //       borderRadius: 10,
          //       fontSize: 11,
          //     },
          //     // 一位数
          //     four: {
          //       backgroundColor: "rgba(0,0,0,0.15)",
          //       color: "white",
          //       width: 12,
          //       height: 16,
          //       padding: [1, 0, 0, 5],
          //       borderRadius: 10,
          //       fontSize: 11,
          //     },
          //     // 两位数
          //     five: {
          //       backgroundColor: "rgba(0,0,0,0.15)",
          //       color: "white",
          //       width: 16,
          //       height: 16,
          //       padding: [1, 0, 0, 1],
          //       borderRadius: 10,
          //       fontSize: 11,
          //     },
          //   },
          // },
        },
        series: [{
          type: "bar",
          showBackground: true,
          barCategoryGap: "100%",
          barWidth: 13,
          label: {
            show: true,
            position: [0, '-14px'],
            offset: [0, 0],
            formatter: '{b}',
            color: "#333",
          },
          itemStyle: {
            align: 'left',
            color: "#5B8FF9",
          },
          data: xdata,
        }],
        dataZoom: [
          {
            type: "slider",
            show: ydata.length > 8,
            startValue: 0,
            endValue: 6,
            width: 6,
            height: '80%',
            top: 'middle',
            right: 4,
            handleSize: 0,
            yAxisIndex: [0, 1],
            // handleStyle: {
            //   borderColor: "#d5dbe4",
            //   borerWidth: "1",
            // },
          },]
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (myChart) myChart.resize();
      })
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    }
  }
}
</script>

<style lang="scss" scoped>
.ranking {
  width: 100%;
  height: 100%;

  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }

  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 34px;

    &-div {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .left {
      font-size: 12px;
      color: #6b798e;
    }

    .right {
      margin-left: 18px;
    }

    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>

<style lang="scss">
.ranking {
  .el-radio-button__inner {
    padding: 6px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}
</style>